/*请求方程序msgreq.c*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>

static struct msgbuf1{
 
 long  mtype;
 
 char  mtext[100];
 
}  sndbuf, rcvbuf, *msgp ;

extern int errno;

main(int argc, char **argv)
{ 
 int rtrn, msgqid ;
 
 char name[10];
 
 double balance;
 
 if (argc!=2){
  fprintf(stderr, "msgreq [01-99]n");
  exit(-1);
 }
 
 if ( (msgqid = msgget(0x810, IPC_CREAT|0660)) == -1 ){
  
  fprintf(stderr, "msgget 887 failed ! msgqid = %dn", msgqid);
  exit(-1);
  
 }
 
 msgp=&sndbuf;
 
 sprintf(sndbuf.mtext,"%2.2s",argv[1]);
 
 printf("输入4位帐号:");
 
 scanf("%s",&sndbuf.mtext[2]);
 
 sndbuf.mtext[6]=0;
 
 msgp->mtype=666;
 
 rtrn=msgsnd(msgqid,msgp, strlen(sndbuf.mtext), 0);
 
 if (rtrn==-1){
  perror("msgsnd");
  exit(-1);
 }
 
 msgp=&rcvbuf;
 
 fprintf(stderr,"等待后台数据处理进程的回答....");
 
 rtrn=msgrcv(msgqid,msgp, 100, atoi(argv[1]), 0);
 
 if(rtrn==-1){
  perror("msgrcv");
  exit(-1);
 }
 
 sscanf(rcvbuf.mtext,"%[^|]|%lf",name,&balance);
 
 printf("n姓名=%sn",name);
 
 printf("余额=%lfn",balance);
 
 exit(0);
}


/*服务方程序msgcenter.c*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>

static struct msgbuf1{
 
 long  mtype;
 
 char  mtext[100];
 
}  sndbuf, rcvbuf , *msgp;

extern int errno;

main()
{ 
 int  rtrn, msgqid ;
 
 char strbuf[100];
 
 if ( (msgqid = msgget(0x810, IPC_CREAT|0660)) == -1 ){
  
  fprintf(stderr, "msgget 887 failed !n");
  exit(-1);
  
 }
 
 while(1) {
        
  msgp=&rcvbuf;
  
  fprintf(stderr,"等待前台进程的请求....");
  
  rtrn=msgrcv(msgqid, msgp, 100, 666 ,MSG_NOERROR);
  if(rtrn==-1){
   perror("msgrcv");
   exit(-1);
  }
 
  msgp=&sndbuf;
  
  sprintf(strbuf,"%2.2s",rcvbuf.mtext);
  
  msgp->mtype=atoi(strbuf);
  
  printf("n输入帐号=%4.4s的帐户姓名:",&rcvbuf.mtext[2]);
  
  scanf("%s",sndbuf.mtext);
  
  strcat(sndbuf.mtext,"|");
  
  printf("输入该帐户余额:");
  
  scanf("%s",strbuf);
  
  strcat(sndbuf.mtext,strbuf);
  
  rtrn=msgsnd(msgqid,msgp, strlen(sndbuf.mtext), 0);
  
  if (rtrn==-1){
   perror("msgsnd");
   exit(-1);
  }
  
 }
 
 exit(0);
}
